<template>
  <a-modal :maskClosable="false" :title="title" centered :width="800" v-model="visible" :confirmLoading="confirmLoading"
    @ok="handleSubmit">
    <a-form :form="form">
      <a-form-item style="display:none">
        <a-input v-decorator="['code']" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="工号">
        <a-input :disabled="isEdit" placeholder="请输入工号"
          v-decorator="['code', { rules: [{ required: true, message: '请输入工号' }] }]" />
        <a-input hidden v-decorator="['id']"></a-input>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="姓名">
        <a-input v-decorator="[
          'name',
          {
            rules: [{ required: true, message: '请输入姓名' }]
          }
        ]" placeholder="请输入姓名" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="头像">
        <UploadImg v-model="imageUrl" cropper />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系电话">
        <a-input placeholder="请输入联系电话"
          v-decorator="['tel', { rules: [{ required: true, message: '请输入联系电话' }, { validator: validatePhone }] }]" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="邮箱">
        <a-input placeholder="请输入邮箱"
          v-decorator="['email', { rules: [{ required: true, message: '请输入邮箱' }, { validator: validateEmail }] }]" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="部门">
        <a-tree-select show-search treeNodeFilterProp="title" style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="treeData"
          v-decorator="['deptId', { rules: [{ required: true, message: '请选择部门' }] }]" placeholder="请选择部门"
          tree-default-expand-all>
        </a-tree-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="职务">
        <a-select :disabled="isMaster" v-decorator="['postId', { rules: [{ required: true, message: '请选择职务' }] }]">
          <a-select-option v-for="(item, index) in postOption" :key="index" :value="item.id">{{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="入职时间">
        <a-date-picker format="YYYY-MM-DD" style="width: 100%;" valueFormat="YYYY-MM-DD" :disabled-date="disabledDate"
          v-decorator="['hireDate', { rules: [{ required: true, message: '请选择入职时间' }] }]" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="账号">
        <a-select placeholder="请选择账号" show-search :filter-option="filterOption" v-decorator="['userId']">
          <a-select-option v-for="(item, index) in loginOption" :key="index" :value="item.userId">{{ item.loginName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
        <a-textarea :rows="5" v-decorator="['remark']" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { getUserList, staffCreate, staffEdit, postList } from '@/api/system/system'
import pick from 'lodash.pick'
import moment from 'moment'
import UploadImg from '@/components/UpFile/uploadImg'

export default {
  components: {
    UploadImg
  },
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      confirmLoading: false,
      roleAll: [],
      mdl: {},
      deptCheck: true,
      imageUrl: '',
      isEdit: false,
      isMaster: false,
      title: '',
      type: '',
      form: this.$form.createForm(this),
      treeData: [],
      postOption: [],
      loginOption: []
    }
  },
  created() {
    this.handlegetRole4AdminAll()
    this.handlePostList()
  },
  methods: {
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取账号
    handlegetRole4AdminAll() {
      var params = {
        pageNum: 1,
        pageSize: 9999,
        status: ''
      }
      return getUserList(params).then(res => {
        this.loginOption = res.rows
      })
    },
    moment,
    disabledDate(current) { return current && current >= this.moment().endOf('day') },
    handlePostList() {
      var params = {
        current: 1,
        size: 9999
      }
      return postList(params).then(res => {
        if (res.code === 0) {
          this.postOption = res.data.records
        }
      })
    },
    add(obj) {
      this.title = obj.title
      this.type = obj.type
      this.imageUrl = ''
      this.visible = true
      this.treeData = obj.dept
      this.form.resetFields()
    },
    edit(obj) {
      this.title = obj.title
      this.type = obj.type
      this.imageUrl = ''
      this.visible = true
      this.treeData = obj.dept
      this.form.resetFields()
      this.$nextTick(() => {
        this.imageUrl = obj.data.avatar
        this.form.setFieldsValue(pick(obj.data, 'id', 'code', 'name', 'orgId', 'deptId', 'postId', 'hireDate', 'tel', 'email', 'remark', 'userId'))
      })
    },
    //   * 校验手机号码
    validatePhone(rule, value, callback) {
      if (!(/^1[3456789]\d{9}$/.test(value)) && value) {
        callback(new Error('手机号码有误，请重填'))
      } else {
        callback()
      }
    },
    //   * 校验邮箱
    validateEmail(rule, value, callback) {
      if (!(/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/.test(value)) && value) {
        callback(new Error('邮箱格式有误，请重填'))
      } else {
        callback()
      }
    },
    onChange(value, label, extra) {
      if (extra.triggerNode.$children.length > 0) {
        this.$message.error('不能选择父节点' + `${label}`)
        this.deptCheck = false
      } else {
        this.deptCheck = true
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      if (!this.deptCheck) {
        this.$message.error('不能选择父节点')
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          var params = JSON.parse(JSON.stringify(values))
          params.avatar = this.imageUrl
          this.confirmLoading = true
          if (this.type === 'add') {
            return staffCreate(params).then(res => {
              this.$message.success('新增成功')
              this.visible = false
              this.$emit('add')
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            return staffEdit(params).then(res => {
              this.$message.success('编辑成功')
              this.visible = false
              this.$emit('upd')
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        }
      })
    }
  }
}
</script>
<style scoped>
</style>
